package com.cmz.common.utils;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 时间工具类
 * @author cmz
 */
public class TimeUtils {

    private volatile long now;

    private TimeUtils() {
        this.now = System.currentTimeMillis();
        this.startTicking();
    }

    private void startTicking() {
        new ScheduledThreadPoolExecutor(1, runnable -> {
            Thread thread = new Thread(runnable, "current-time-millis");
            thread.setDaemon(true);
            return thread;
        }).scheduleAtFixedRate(() -> {
            now = System.currentTimeMillis();
        }, 1, 1, TimeUnit.MILLISECONDS);
    }

    private long getNow() {
        return this.now;
    }

    private static class SingletonHolder {
        private static final TimeUtils INSTANCE = new TimeUtils();
    }

    /**
     * 获取当前时间（毫秒数）
     * @return 当前时间
     */
    public static long getCurrentTimeMillis() {
        return SingletonHolder.INSTANCE.getNow();
    }

}
